package com.carnation.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.carnation.bean.FTPFileInfo;
import com.carnation.service.Ftp;
import com.carnation.service.impl.FTPServerImpl;
import com.carnation.service.impl.SFTPServerImpl;
import com.carnation.utils.MenuFileUtril;
import com.google.gson.Gson;

public class RemoteFileServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(RemoteFileServlet.class);
	
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		String path = httpServletRequest.getParameter("path");
		if(path == null || path.isEmpty()){
			path = "/";
		}
		MenuFileUtril menuFileUtril = new MenuFileUtril();
		Ftp ftp = null;
		System.out.println(path);
		if(menuFileUtril.getFTPProtocol().toLowerCase().equals("ftp")){
			ftp = new FTPServerImpl();
		}
		else if(menuFileUtril.getFTPProtocol().toLowerCase().equals("sftp")){
			ftp = new SFTPServerImpl();
		}
		else{
			ftp = null;
		}
		if(ftp == null){
			System.out.println("未知协议");
		}
		else{
			Gson gson = new Gson();
			try {
				String realPath = ftp.getPath(path);
				List<FTPFileInfo> list = ftp.getFtpFileInfoByParent(realPath);
				httpServletResponse.setCharacterEncoding("UTF-8");
				try{
					httpServletResponse.getWriter().write(gson.toJson(list));
					httpServletResponse.getWriter().close();
				}
				catch(IOException e){
					logger.error("写报文出错",e);
				}
			} catch (Exception e1) {
				logger.error("获取路径出错",e1);
			}
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		doPost(httpServletRequest, httpServletResponse);
	}
}
